package hvzt.minimap.activities;

import hvzt.minimap.R;
import hvzt.minimap.ambassador.Ambassador;
import hvzt.minimap.asynctasks.Progress;
import hvzt.minimap.location.LocationService;
import iface.Registration;
import iface.Status;
import iface.UserTypes;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;

/**
 * RegistrationActivity responsible for UI for registrating users into a game
 * and setting android shared preferences such that app knows next time
 * to go to map directly. 
 * @author JosephM
 */
public class RegistrationActivity extends Activity implements OnClickListener, ServerActivity{
	
	private EditText netIdField;
	private EditText phoneNumberField;
	private String registration;
	private Spinner playerTypeSpinner;
	private AlertDialog alert;
	ProgressBar spinner;
	
	// override method from extending activity to setup xml layout and UI
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reg);
		setUpUI();
	}
	
	// private helper method to help setup UI
	private void setUpUI() {
		netIdField = (EditText)findViewById(R.id.net_id_field);
		phoneNumberField = (EditText)findViewById(R.id.phone_number_field);
		// auto-get users phone number to input register with. 
		TelephonyManager tMgr =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		String phoneNumber = tMgr.getLine1Number();
		phoneNumberField.setText(phoneNumber);
		registration = null;
		spinner = (ProgressBar)findViewById(R.id.spinner);
		spinner.setVisibility(View.	INVISIBLE);
		
		playerTypeSpinner = (Spinner)findViewById(R.id.player_type_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.player_type_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		playerTypeSpinner.setAdapter(adapter);
	}

	// onClick method for when user clicks on register.
	@Override
	public void onClick(View v) {
		String netId = netIdField.getText().toString();
		String phoneNumber = (phoneNumberField.getText().toString());
		String playerType = playerTypeSpinner.getSelectedItem().toString();
		Log.e(LocationService.TAG, "playerType = " + playerType);
		UserTypes type = null;
		if (playerType.equalsIgnoreCase(UserTypes.HUMAN.toString())) {
			Log.e(LocationService.TAG, "HUMAN chosen");
			type = UserTypes.HUMAN;
		} else if (playerType.equalsIgnoreCase(UserTypes.ZOMBIE.toString())) {
			Log.e(LocationService.TAG, "ZOMBIE chosen");
			type = UserTypes.ZOMBIE;
		} else {
			Log.e(LocationService.TAG, "OBSERVER chosen");
			type = UserTypes.OBSERVER;
		}
		// empty/null netId field
		if (netId.length() == 0 || netId == null) {
			showDialog(0);
		// if phone number is not valid 10/11 digit phone number, or if null
		} else if (phoneNumber.length() < 10 || phoneNumber.length() > 11 || netId == null) {
			showDialog(1);
		} else {
			Registration reg = new Registration(netId, type, phoneNumber);
			Ambassador.getInstance().sendRegistration(reg, this);
		}
	}

	// method to show progress spinner depending on progress returned from registration task
	@Override
	public void updateProgress(Progress progress) {
		Log.e("updateProgress", progress.toString());
		if (progress == Progress.IN_PROGRESS) {
			spinner.setVisibility(View.VISIBLE);
		} else {
			spinner.setVisibility(View.INVISIBLE);
		}
	}

	// method to handle results from registration tasks to properly show results
	@Override
	public void handleResult(Status result) {
		Log.e("handleresults", result.toString());
		registration = result.toString();
		if (result.getMessageStatus() == Status.Result.ERROR || result.getMessageStatus() == Status.Result.INVALID) {
			showDialog(2);
		} else {
			// set shared preferences of android for hvzt for the input fields.
			SharedPreferences.Editor editor = getSharedPreferences("hvzt", MODE_PRIVATE).edit();
			editor.putBoolean("registered", true);
			editor.putString("netId", netIdField.getText().toString());
			editor.putString("telephone", phoneNumberField.getText().toString());
			editor.commit();
			showDialog(3);
//			Intent intent = new Intent(InitActivity.getTheActivity(), ZMapActivity.class);
//			startActivity(intent);
//			finish();
		}
	}
	
	// dialogs to show for results from server when user registers. 
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch(id) {
		case 0:
			builder.setMessage("Invalid netId format").setCancelable(true);
			break;
		case 1:
			builder.setMessage("Invalid phone number format").setCancelable(true);
			break;
		case 2:	
			builder.setMessage(registration).setCancelable(true);
			break;
		case 3:
			builder.setMessage("Registration Successful! Going to map").setCancelable(false)
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(RegistrationActivity.this, ZMapActivity.class);
					startActivity(intent);
					finish();
				}
			});
			break;
		}
		alert = builder.create();
		return alert;
	}
	
	// method to override so that the error message is properly updated each time 
	// the registration screen gets loaded
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch(id) {
		case 2:	
			AlertDialog alertDialog = (AlertDialog) dialog;
            alertDialog.setMessage(registration);
            break;
		}
		super.onPrepareDialog(id, dialog);
	}
	
	@Override
	protected void onDestroy() {
		if (alert != null)
			alert.cancel();
		super.onDestroy();
	}
}